#include "ReactiveEnemy.h"
#include "..\GameEngine.h"
#include "AbstractClasses\GameEntity.h"
#include "..\Dependencies.h"
#include "..\Games\MyGame.h"
#include "..\Scene\SceneManager.h"
#include <fstream>
#include <iostream>
#include <algorithm>

ReactiveEnemy::ReactiveEnemy(int maxFrequency, std::string name) : Enemy(maxFrequency, name) {
	moveActions.push_back(LEFT);
	moveActions.push_back(RIGHT);
	if(name.compare("reactiveenemy2") == 0) {
		moveActions.push_back(UP);
		moveActions.push_back(DOWN);
	}
	this->lastShotFired = 0;
}

ReactiveEnemy::~ReactiveEnemy() {
}

void ReactiveEnemy::reset(){}

int ReactiveEnemy::getType() {
	return REACTIVEENEMY;
}

void ReactiveEnemy::draw()
{	
	SCALE scale = {0.2,0.2,0.2};
	GameEngine::Instance()->getRenderer()->drawPieceQuad("assets/spaceship3.raw\0", 1,1,1, this->getPosition(),this->getOrientation(), scale, 128,128,getColor());
}

void ReactiveEnemy::actualUpdate(unsigned long long timePassed)
{
	doSomething();
	if(timePassed - this->lastShotFired > 1000 || this->getMySceneNode()->getChildren().size() == 0) {
		this->lastShotFired = timePassed;
		POINT3D shipPOS = this->getPosition();
		ORIENTATION shipOR = this->getOrientation();
		shipPOS.x += 0.5f;
		shipPOS.y -= 0.5f;
		MyGame::Instance()->createEntity(this->getMySceneNode(),0,SHIPSHOT,40,"reactiveenemyshot",shipOR,shipPOS,this->getColor());
	}
}

void ReactiveEnemy::sense() {
	//evaluate(getPosition());
}
void ReactiveEnemy::reason() {
	if(plan.size() == 0) {					//If the plan is empty
		plan.push_back(bestImprovement());	//Do a best improvement move
		//plan.push_back(SHOOT);
	}	
}
float ReactiveEnemy::evaluate(POINT3D position) {
	float utility = 1.0;													//The eventual utility
	SceneNode * n = SceneManager::Instance()->getRootSceneNode();
	GameEntity * ship = n->getEntity("ship");
	TyrianEnvironment * e = MyGame::Instance()->getEnv();
	utility = 1.0 - (e->distance(position, ship->getPosition())/64);		//The initial utility is 1 minus the distance to the ship divided by the maximum distance
	
	int count = 1;
	std::list<SceneNode *>::iterator it;	
	std::list<SceneNode *> children = ship->getMySceneNode()->getChildren();
	for(it=children.begin(); it != children.end(); ++it) {	//Iterate over all children of the ship, they are its bullets
		utility += min(e->distance(position, (*it)->getPosition())/15, 1.5);//The utility cannot increase, but only decrease, the maximum utility is therefore sUtility and this value depends on the distance to the shot
		count++;
	}
	utility /= count;
	return utility;
}